# -*- coding: utf-8 -*-
"""
Created on Wed Mar  4 16:04:12 2020

@author: 张伟琛
"""

import time
import os
import psutil
import multiprocessing
import pandas as pd
import copy


class process_manager:

    def __init__(self):

        # 没这个运行不了多进程
        multiprocessing.freeze_support()
        self.work_path = os.getcwd()

    def get_current_process(self):
        # 进程个数
        self.process_dict = {}
        self.process_id_dict = {}

        # 获取当前所有进程
        process_id_list = psutil.pids()
        for process_id in process_id_list:
            try:
                process = psutil.Process(process_id)
                process_name = str(process.name)
                self.process_dict[process_name] = process
                self.process_id_dict[process_name] = process_id
            except:
                pass
        self.process_name_list = list(self.process_dict.keys())

    def multi_process(self, status, stg_id, path):

        # 策略进程，根据状态判断所需要进行的操作
        if status == 5:
            print('start_process')
            # process = multiprocessing.Process(target=self.start_process,args=(path,status))
            self.start_process(path)
        elif status == 6:
            print('end_process')
            # process = multiprocessing.Process(target=self.end_process,args=(stg_id,status))
            self.end_process(stg_id)
        # process.start()

    def start_process(self, path):

        # 启动
        isExists = os.path.exists(path)
        # 判断结果
        if not isExists:
            print('启动进程失败')
            return False
        else:
            # os.popen(f'start {path}')
            # import subprocess
            # os.popen(f'nohup {path} &')
            # print('before Popen',os.environ['PATH'])
            # subprocess.Popen(['python3','-u', path, '&'],preexec_fn=os.setpgrp)
            path_list = path.split('/')
            print("path_list, ", path_list)
            chr_path = ('/').join(path_list[:-1])
            print("path, ", path)
            os.chdir(chr_path)
            # os.popen(f'nohup {path} &')
            # os.popen(f'{path}')
            os.system(f'{path}')
            os.chdir(self.work_path)
            print("work_path, ", self.work_path)
            # subprocess.Popen(['nohup', path, '&'],preexec_fn=os.setpgrp,cwd=chr_path)
            # os.system(f'{path}')
            print('启动成功')
            return True

            # def start_process(self, path):

        # 启动
        # isExists = os.path.exists(path)
        # 判断结果
        # if not isExists:
        #    print('启动进程失败')
        #    return False
        # else:
        # os.popen(f'start {path}')
        #    os.popen(f'nohup `{path}` &')
        #    print('启动成功')
        #    return True

    def end_process(self, stg_id):

        # 停止
        try:
            for process_name in self.process_name_list:
                if stg_id in process_name:
                    process = self.process_dict[process_name]
                    # process.terminate()
                    process_id = self.process_id_dict[process_name]
                    print(process_id)
                    os.system(f'kill {process_id}')
                    print('关闭成功')
                    return True
        except Exception as e:
            print('关闭进程失败, 错误原因 : ', e)
            return False


if __name__ == '__main__':
    main = process_manager('')
    main.get_current_process()
#    main.multi_process()
#    time.sleep(2)
#    main.end_process('trader')
